package com.linked.usermanage.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.universal.common.Result;
import com.linked.usermanage.address.service.IAddressService;
import com.linked.usermanage.user.bean.dto.UserAddressDTO;
import com.linked.usermanage.user.service.IUserAddressService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author :dbq
 * @date : 2023/1/13 10:00
 * @description : desc
 */
@Slf4j
@RestController
@RequestMapping("useraddress")
public class UserAddressController {

    private final IAddressService addressService;

    private final IUserAddressService userAddressService;

    private final ObjectMapper mapper;

    @Autowired
    public UserAddressController(IAddressService addressService, IUserAddressService userAddressService, ObjectMapper mapper) {
        this.addressService = addressService;
        this.userAddressService = userAddressService;
        this.mapper = mapper;
    }

    @PostMapping("queryUserAddressList")
    Result queryUserAddressList(@NonNull String userId) throws Exception {
        List<UserAddressDTO> addressList = addressService.queryUserAddressList(userId);
        return CollectionUtils.isEmpty(addressList) ? Result.ok(false, "未查询到用户地址！") : Result.success(addressList);
    }

    @PostMapping("saveUserAddress")
    Result saveUserAddress(@RequestBody UserAddressDTO param) throws Exception {

        if (log.isInfoEnabled()) {
            log.info("保存用户地址接口 入参：{}", mapper.writeValueAsString(param));
        }
        boolean ret = false;
        try {
            ret = userAddressService.saveUserAddress(param);
        } catch (Exception e) {
            log.error("保存用户地址接口异常", e);
            return Result.error();
        }
        return ret ? Result.ok(true, "保存成功") : Result.ok(false, "保存失败");
    }

}
